package com.web.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.web.model.User;
import com.web.service.ServiceDAOFactory;
import com.web.service.UserService;
import com.web.util.Md5Code;

@WebServlet("/login.do")
public class LoginServlet extends HttpServlet {

	public static final String METHOD_TOLOGIN = "0";
	public static final String METHOD_LOGIN = "1";
	private static final long serialVersionUID= 7893349575794L;
	
	@Override
	protected void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException{
		doPost(req,resp);
	}
	
	@Override 
	protected void doPost(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException{
		String method=req.getParameter("method");
		if(method !=null){
			switch(method){
			case LoginServlet.METHOD_TOLOGIN:
				req.getRequestDispatcher("/WEB-INF/view/user/login_form.jsp").forward(req, resp);
				break;
			case LoginServlet.METHOD_LOGIN:
				try{
					login(req,resp);
				}catch(Exception e){
					e.printStackTrace();
				}
				break;
				default:
					break;
			}
		}
	}
	
	private void login(HttpServletRequest req,HttpServletResponse resp) throws Exception{
		//验证email和密码是否正确，不正确返回login_form.jsp
		UserService userService = ServiceDAOFactory.getUserService();
		User user=userService.findByEmail(req.getParameter("email"));
		if(user == null || !user.getPassword().equals(Md5Code.createMd5Code(req.getParameter("password")))){
		//if(user == null || !user.getPassword().equals(req.getParameter("password"))){
			req.setAttribute("login_err", "用户或密码错误");
			req.getRequestDispatcher("/WEB-INF/view/user/login_form.jsp").forward(req, resp);
			
		}
			
		//更新last_login_time,last_login_ip字段
		user.setLastLoginIp(req.getRemoteAddr());
		user.setLastLoginTime(System.currentTimeMillis());
		userService.update(user);
		//将user信息写入session
		req.getSession().setAttribute("s_user", user);
		//检查is_email_verify是否为true，如果没有验证，返回到verify_form.jsp页面
		if(!user.isEmailVerify()){
			req.getRequestDispatcher("/WEB-INF/view/user/verify_form.jsp").forward(req, resp);
			return ;
		}
		resp.sendRedirect("/TaoShuZhai/index.jsp");
//		req.getRequestDispatcher("/WEB-INF/view/home/main.jsp").forward(req, resp);
	}
	
	
}
